package com.example.lottery.controller;


import com.example.lottery.common.errorcode.ControllerErrorCodeConstants;
import com.example.lottery.common.exception.ControllerException;
import com.example.lottery.common.pojo.CommonResult;
import com.example.lottery.common.utils.JacksonUtil;
import com.example.lottery.controller.param.UserLoginMessage;
import com.example.lottery.controller.param.UserLoginPassword;
import com.example.lottery.controller.param.UserRegisterParam;
import com.example.lottery.controller.result.BaseUserInfoResult;
import com.example.lottery.controller.result.UserLoginResult;
import com.example.lottery.controller.result.UserRegisterResult;
import com.example.lottery.service.UserService;
import com.example.lottery.service.dto.UserDTO;
import com.example.lottery.service.dto.UserLoginDTO;
import com.example.lottery.service.dto.UserRegisterDTO;
import com.example.lottery.service.enums.UserIdentityEnum;
import com.example.lottery.service.impl.VerificationCodeServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private VerificationCodeServiceImpl verificationCodeService;

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    /**
     * 注册(前端获取URL来获取admin，通过identity: (admin == null || admin === 'true') ? "ADMIN" : "NORMAL"来进行获取用户的身份信息传递给后端)
     * url是不会给admin进行创建，所以在登录界面进行注册时，admin== null所以此时注册的就是管理员ADMIN
     * 在管理员界面进行注册普通用户是，admin2.html代码中存在page = $(this).attr('href') + "?param=" + randomParam + "&jumpList=true&admin=false";将admin设置为false
     * 此时注册的用户的identity就是NORMAL也就是普通用户
     * @param param
     * @return
     */
    @RequestMapping("/register")
    public CommonResult<UserRegisterResult> register(@Validated @RequestBody UserRegisterParam param) {
        //打印日志
        logger.info("register param: {}", JacksonUtil.writeValueAsString(param));
        //调用service层服务
        UserRegisterDTO userRegisterDTO = userService.register(param);
        return CommonResult.success(convertToUserRegisterResult(userRegisterDTO));
    }

    /**
     * 邮箱登录验证码获取
     * @param email
     * @return
     */
    @RequestMapping("/verification")
    public CommonResult<Boolean> sendVerificationCode(String email) {
        logger.info("sendVerificationCode email: {}", email);
        verificationCodeService.sendVerificationCode(email);
        return CommonResult.success(true);
    }

    /**
     * 管理员密码登录
     * @param param
     * @return
     */
    @RequestMapping("/password/login")
    public CommonResult<UserLoginResult> userPasswordLogin(@Validated @RequestBody UserLoginPassword param) {
        UserLoginDTO userLoginDTO = userService.login(param);
        return CommonResult.success(convertToUserLoginResult(userLoginDTO));
    }

    /**
     * 管理员邮箱验证码
     * @param param
     * @return
     */
    @RequestMapping("/message/login")
    public CommonResult<UserLoginResult> userMessageLogin(@Validated @RequestBody UserLoginMessage param) {
        UserLoginDTO userLoginDTO = userService.login(param);
        return CommonResult.success(convertToUserLoginResult(userLoginDTO));
    }

    /**
     * 返回登录结果的包装
     * @param userLoginDTO
     * @return
     */
    private UserLoginResult convertToUserLoginResult(UserLoginDTO userLoginDTO) {
        if (userLoginDTO == null) {
            throw new ControllerException(ControllerErrorCodeConstants.LOGIN_ERROR);
        }
        UserLoginResult userLoginResult = new UserLoginResult();
        userLoginResult.setIdentity(userLoginDTO.getIdentity().name());
        userLoginResult.setToken(userLoginDTO.getToken());
        return userLoginResult;
    }

    /**
     * 返回注册结果包装
     * @param userRegisterDTO
     * @return
     */
    private UserRegisterResult convertToUserRegisterResult(UserRegisterDTO userRegisterDTO) {
        UserRegisterResult result = new UserRegisterResult();
        if (userRegisterDTO == null) {
             throw new ControllerException(ControllerErrorCodeConstants.REGISTER_ERROR);
        }
        result.setUserId(userRegisterDTO.getUserId());
        return result;
    }


    /**
     * 在管理员界面获取当前存在用户的列表
     * @param identity
     * @return
     */
    @RequestMapping("/find-list")
    public CommonResult<List<BaseUserInfoResult>> findBaseUserInfo(String identity) {
        logger.info("findBaseUserInfo identity: {}", identity);
        List<UserDTO> userDTOList = userService.findBaseUserInfo(UserIdentityEnum.getByName(identity));
        return CommonResult.success(convertToList(userDTOList));
    }

    /**
     * 对用户列表的返回前端结果进行包装
     * @param userDTOList
     * @return
     */
    private List<BaseUserInfoResult> convertToList(List<UserDTO> userDTOList) {
        //判断列表不为空,为空返回空列表
        if (CollectionUtils.isEmpty(userDTOList)) {
            return Arrays.asList();
        }

        //包装成前端所需要数据的格式对象
        return userDTOList.stream().map(userDTO -> {
            BaseUserInfoResult result = new BaseUserInfoResult();
            result.setUserId(userDTO.getUserId());
            result.setUserName(userDTO.getUserName());
            result.setIdentity(userDTO.getIdentity().name());
            return result;
        }).collect(Collectors.toList());
    }
}
